package com.blackfish.desktop;

import com.blackfish.active.ActiveService;
import com.blackfish.bag.BagService;
import com.blackfish.common.model.Bag;
import com.blackfish.common.model.Device;
import com.blackfish.common.model.Module;
import com.blackfish.module.ModuleService;
import com.blackfish.path.PathService;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.List;

public class DesktopService {
	private static final  BagService bagService = new BagService();
	private static final  ModuleService moduleService = new ModuleService();
	private static final ActiveService activeService = new ActiveService();
	private static final PathService pathService = new PathService();
	
	public List<Bag> deskBagList(){
		return bagService.findAll("1");
	}

	public List<Bag> deskBagList(String user_id){
		return bagService.findAll(user_id);
	}

	public List<Record> deskUserBagList(String user_id){
		return bagService.findUserAll(user_id);
	}
	
	public List<Module> deskModuleList(String bag){
		return moduleService.findAll(bag);
	}
	
	public String replyActive(String actName){
		String s;
		try{
			s = activeService.findByViewname(actName);
		}catch (Exception e){
			s = null;
		}
		return (s==null)?actName:s;
	}
	
	public String getBagName(int id){
		return bagService.findById(id).getName();
	}
	
	public String getPathById(int id){
		return pathService.findById(id).getPath();
	}

	public int getModuleId(String moduleName,String bagName){
		int bagId = bagService.getIdByName(bagName);
		Module module = Module.dao.findFirst("select * from module where bag_id="+bagId+" and name=\""+moduleName+"\"");
		return module.getId();
	}

	public int getModuleId(String moduleName,String bagName,int userId){
		// int bagId = bagService.getIdByName(bagName);
		Module module = Module.dao.findFirst("select m.* from module as m inner join bag as b inner join bag_belong as bb on bb.user_id="+userId+" and b.name=\""+bagName+"\" and m.name=\""+moduleName+"\" and m.bag=b.id");
		return module.getId();
	}

	public List<Record> getModuleByUser(String moduleName,String bagName,String userName){
		return Db.find("");
	}


	public List<String> getDeviceId(int moduleId)  {
		List<String> deviceKeys = new ArrayList<String>();
		List<Record> devices = Db.find("select * from device as d INNER JOIN info as i on d.id=i.device_id and i.module_id="+moduleId);
		for(Record r:devices){
			deviceKeys.add(r.getStr("init_key"));
		}
		return deviceKeys;
	}
}
